package com.lbs.jiepiaisi.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.base.BaseActivity;
import com.lbs.jiepiaisi.bean.CityEntity;
import com.lbs.jiepiaisi.biz.ChengShiLieBiaoBiz;
import com.lbs.jiepiaisi.manager.App;
import com.lbs.jiepiaisi.style.citylist.CityListSelectActivity;
import com.lbs.jiepiaisi.style.citylist.bean.CityInfoBean;
import com.lbs.jiepiaisi.style.citylist.utils.CityListLoader;
import com.lbs.jiepiaisi.utils.Constant;

import android.widget.AdapterView.OnItemClickListener;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 时间：2017/11/6 14:54
 * 作用：城市列表
 */

public class ChengShiLieBiaoActivity extends BaseActivity implements OnItemClickListener,TextWatcher{
    String[] letter={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};

    List<CityEntity.Result.Item> letterToCity=new ArrayList<>();
    List<CityEntity.Result.Item> letterToCityTemp=new ArrayList<>();
    MyAdapter cityAdapter;
    ListView lv;

    ListView lv1;

    CityEntity cityEntity;

    private EditText searchEt;

    private ChengShiReceiver chengshiReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isTemplate=true;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chengshiliebiao);
        titleView.setText("城市列表");
        chengshiReceiver=new ChengShiReceiver();
        registerReceiver(chengshiReceiver, new IntentFilter(Constant.CHENG_SHI_XIN_XI));
        ChengShiLieBiaoBiz chengShiLieBiaoBiz=new ChengShiLieBiaoBiz();
        chengShiLieBiaoBiz.chengShiLieBiaoBiz();
//        lv=(ListView)findViewById(R.id.listView1);
//        lv.setOnItemClickListener(this);
//        lv1=(ListView)findViewById(R.id.listView2);
//        lv1.setOnItemClickListener(this);
//        searchEt = (EditText)findViewById(R.id.et_search);
//        searchEt.addTextChangedListener(this);

        /**
         * 预先加载一级列表显示 全国所有城市市的数据
         */
        CityListLoader.getInstance().loadCityData(this);
        Intent intent = new Intent(ChengShiLieBiaoActivity.this, CityListSelectActivity.class);
        startActivityForResult(intent, CityListSelectActivity.CITY_SELECT_RESULT_FRAG);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if("".equals(searchEt.getText().toString())){
            letterToCity = letterToCityTemp;
        }else {
            letterToCity.clear();
            for(CityEntity.Result.Item item : letterToCityTemp){
                if(item.getCityName().contains(s)){
                    letterToCity.add(item);
                }

            }
        }
        if(cityAdapter != null){
            cityAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(chengshiReceiver);
    }

    class MyAdapter1 extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return letter.length;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return letter[position];
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view= LayoutInflater.from(ChengShiLieBiaoActivity.this).inflate(R.layout.letter_list, null);
            TextView tv=(TextView)view.findViewById(R.id.letterListTextView);
            tv.setText(letter[position]);
            return view;
        }
    }

    class MyAdapter extends BaseAdapter{

        final static int TYPE_1=1;
        final static int TYPE_2=2;

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return letterToCity.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return letterToCity.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public int getItemViewType(int position) {
            for(int i=0;i<letter.length;i++){
                if(letterToCity.get(position).equals(letter[i])){
                    return TYPE_1;
                }
            }
            return TYPE_2;
        }

        @Override
        public int getViewTypeCount() {
            return 3;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            /**
             * 即使convertView缓存了一些布局，但是在重构时，根本不知道怎么样去让convertView返回你所需要的布局，这时你需
             * 要让adapter知道我当前有哪些布局，我重构Item时的布局选取规则，好让convertView能返回你需要的布局。
             * 需要重写以下两个函数
             * @Override
             * public int getItemViewType(int position) {}这个函数获取在getView中创建的视图的类型
             * @Override
             * public int getViewTypeCount() {}返回在getView中创建视图类型的数量
             * 至于这两个方法的详细用处，自己看api即可
             */
            ViewHolder1 vh1=null;
            ViewHolder2 vh2=null;
            int type=getItemViewType(position);
            if(convertView==null){
                switch (type) {
                    case TYPE_1:
                        convertView=LayoutInflater.from(ChengShiLieBiaoActivity.this).inflate(R.layout.letter, null);
                        vh1=new ViewHolder1();
                        vh1.tv=(TextView)convertView.findViewById(R.id.letterTextView);
                        convertView.setTag(vh1);
                        break;
                    case TYPE_2:
                        convertView=LayoutInflater.from(ChengShiLieBiaoActivity.this).inflate(R.layout.city, null);
                        vh2=new ViewHolder2();
                        vh2.tv=(TextView)convertView.findViewById(R.id.cityTextView);
                        convertView.setTag(vh2);
                        break;
                    default:
                        break;
                }
            }else{
                switch (type) {
                    case TYPE_1:
                        vh1=(ViewHolder1)convertView.getTag();
                        break;
                    case TYPE_2:
                        vh2=(ViewHolder2)convertView.getTag();
                        break;
                    default:
                        break;
                }
            }
            switch (type) {
                case TYPE_1:
                    //vh1.tv.setText(letterToCity.get(position));
                    vh1.tv.setText(letterToCity.get(position).getCityName());
                    break;
                case TYPE_2:
                    vh2.tv.setText(letterToCity.get(position).getCityName());
                    break;
                default:
                    break;
            }
            return convertView;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        switch (parent.getId()) {
            case R.id.listView1:
                boolean  isLetter=false;
                for(int i=0;i<letter.length;i++){
                    if(letter[i].equals(letterToCity.get(position))){
                        isLetter=true;
                        break;
                    }
                }
                if(!isLetter){
                    Toast.makeText(this, letterToCity.get(position).getCityName(), Toast.LENGTH_SHORT).show();
                    //发送选择的城市
                    Intent intent = new Intent(Constant.SHI_MING_CHENG);
                    intent.putExtra(Constant.KEY_DATA, letterToCity.get(position).getCityName());
                    intent.putExtra(Constant.KEY_DATA2, letterToCity.get(position).getCityCode());
                    intent.putExtra(Constant.KEY_DATA3, letterToCity.get(position));
                    App.instance.sendBroadcast(intent);
                    finish();

                }
                break;
            case R.id.listView2:
                for(int i=0;i<letterToCity.size();i++){
                    if(letter[position].equals(letterToCity.get(i))){
                        lv.setSelection(i);
                        break;
                    }
                }
                break;
            default:
                break;
        }
    }

    class ChengShiReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            cityEntity=(CityEntity) intent.getSerializableExtra(Constant.KEY_DATA);

            letterToCity = cityEntity.getResult().getItems();
            for(CityEntity.Result.Item item : letterToCity){
                letterToCityTemp.add(item);
            }
            if(cityEntity.getStatus().equals("0")){

                Toast.makeText(mContext, "加载成功", Toast.LENGTH_SHORT).show();

                Log.e("TAG","加载成功！！");
//                cityAdapter = new MyAdapter();
//                lv.setAdapter(cityAdapter);
//
//                lv1.setAdapter(new MyAdapter1());


            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CityListSelectActivity.CITY_SELECT_RESULT_FRAG) {
            if (resultCode == RESULT_OK) {
                if (data == null) {
                    return;
                }
                Bundle bundle = data.getExtras();

                CityInfoBean cityInfoBean = (CityInfoBean) bundle.getParcelable("cityinfo");

                if (null == cityInfoBean) {
                    return;
                }

            }
        }
    }
}


    class ViewHolder{
        TextView tv;
        LinearLayout ll;
    }
    class ViewHolder1{
        TextView tv;
    }
    class ViewHolder2{
        TextView tv;
    }





